<?php

namespace App\Exports;

use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithStrictNullComparison;
use Maatwebsite\Excel\Events\AfterSheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;

class MillinglistExport implements FromCollection, WithEvents , WithStrictNullComparison
{
    use Exportable;

    protected $params;
    protected $count;

    public function __construct(array $params)
    {
        $this->params = $params;
    }
       
    public function collection()
    {
        // 这里使用 collect 方法生成 collection，通常模型取出的数据即为 collection 格式
        $collection = new Collection($this->createData());
        return $collection;
    }

    protected function createData()
    {
        $heading = [
            ['铣刀更换记录','','','','','','','',''],
            ['数据导出日期：'.date('Y年m月d日'),'','','','','','','',''],
            ['封边机名称','换刀阈值','工作面积','铣刀编码','更换人','更换时间','备注','创建时间','修改时间'],
        ];
        $data = $this->queryData($this->params);
        $this->count = count($data);
        return array_merge($heading, $data);
    }
    //获取配件操作记录列表
    protected function queryData($request)
    {
        $min_time = $request['min_time'] ?? '';
        $max_time = $request['max_time'] ?? '';
        $datas = DB::table('k_change_milling_cutter_apply AS cmcy')
            ->leftJoin('k_bag_sealer AS bs', 'bs.id', '=', 'cmcy.bs_id')
            ->leftJoin('users AS change_cutter_u', 'change_cutter_u.uid', '=', 'cmcy.change_cutter_uid')
            ->when($min_time AND $max_time, function ($query) use ($min_time,$max_time) {
                return $query->where('cmcy.created_at', '>=', $min_time)
                    ->where('cmcy.created_at', '<=', $max_time);
            })
            ->select([
                'cmcy.*',
                'bs.machine_name AS machine_name',
                'bs.area_thresholds AS area_thresholds',
                'change_cutter_u.name AS change_cutter_name',
            ])
            ->where('cmcy.status',3)
            ->orderBy("cmcy.created_at", "desc")
            ->get()->toArray();
        $res = [];
        foreach ($datas as $k=>$datum)
        {
            $res[$k][]= $datum->machine_name;//封边机名称
            $res[$k][]= $datum->area_thresholds;//换刀阈值
            $res[$k][]= $datum->sum_area;//工作面积
            $res[$k][]= $datum->change_milling_cutter;//工作面积
            $res[$k][]= $datum->change_cutter_name;//工作面积
            $res[$k][]= $datum->change_cutter_at;//工作面积
            $res[$k][]= $datum->remark;//备注
            $res[$k][]= $datum->created_at;//创建时间
            $res[$k][]= $datum->updated_at;//修改时间
        }
        return $res;
    }

    /**
     * 注册事件
     * @return array
     */
    public function registerEvents(): array
    {
        return [
            AfterSheet::class  => function(AfterSheet $event) {
                //设置列宽
                $event->sheet->getDelegate()->getColumnDimension('A')->setWidth(20);
                $event->sheet->getDelegate()->getColumnDimension('B')->setWidth(20);
                $event->sheet->getDelegate()->getColumnDimension('C')->setWidth(20);
                $event->sheet->getDelegate()->getColumnDimension('D')->setWidth(20);
                $event->sheet->getDelegate()->getColumnDimension('E')->setWidth(20);
                $event->sheet->getDelegate()->getColumnDimension('F')->setWidth(20);
                $event->sheet->getDelegate()->getColumnDimension('G')->setWidth(20);
                $event->sheet->getDelegate()->getColumnDimension('H')->setWidth(20);
                $event->sheet->getDelegate()->getColumnDimension('I')->setWidth(20);
                //设置区域单元格字体、颜色、背景等，其他设置请查看 applyFromArray 方法，提供了注释
                $event->sheet->getDelegate()->getStyle('A1:I1')->applyFromArray([
                    'alignment' => [
                        'horizontal' => Alignment::HORIZONTAL_CENTER,
                        'vertical' => Alignment::VERTICAL_CENTER,
                        'wrapText' => true,
                    ],
                    'font' => [
                        'name' => '等线',
                        'size' => '22',
                        'bold' => true,
                        'italic' => false,
                        'strikethrough' => false,
                    ],
                ]);
                $event->sheet->getDelegate()->getStyle('A2:I2')->applyFromArray([
                    'font' => [
                        'name' => 'Arial',
                        'bold' => true,
                        'italic' => false,
                        'strikethrough' => false,
                        'color' => [
                            'rgb' => 'FF0000'
                        ]
                    ]
                ]);
                $event->sheet->getDelegate()->getStyle('A3:I3')->applyFromArray([
                    'alignment' => [
                        'horizontal' => Alignment::HORIZONTAL_CENTER,
                        'vertical' => Alignment::VERTICAL_CENTER,
                        'wrapText' => true,
                    ],
                    'font' => [
                        'name' => 'Arial',
                        'bold' => true,
                        'italic' => false,
                        'strikethrough' => false,
                        'color' => [
                            'rgb' => '4472C4'
                        ]
                    ],
                    'borders' => [
                        'allBorders' => [
                            'borderStyle' => Border::BORDER_THIN,
                            'color' => [
                                'rgb' => '808080'
                            ]
                        ]
                    ],
                    'fill' => [
                        'fillType' => 'linear', //线性填充，类似渐变
                        'rotation' => 45, //渐变角度
                        'startColor' => [
                            'rgb' => 'F2F2F2' //初始颜色
                        ],
                        //结束颜色，如果需要单一背景色，请和初始颜色保持一致
                        'endColor' => [
                            'argb' => 'F2F2F2'
                        ]
                    ],
                ]);
                $event->sheet->getDelegate()->getStyle('A4:I'.(3+$this->count))->applyFromArray([
                    'alignment' => [
                        'horizontal' => Alignment::HORIZONTAL_CENTER,
                        'vertical' => Alignment::VERTICAL_CENTER,
                        'wrapText' => true,
                    ],
                    'borders' => [
                        'allBorders' => [
                            'borderStyle' => Border::BORDER_THIN,
                            'color' => [
                                'rgb' => '808080'
                            ]
                        ]
                    ],
                ]);

                //合并单元格
                $event->sheet->getDelegate()->mergeCells('A1:I1');
                $event->sheet->getDelegate()->mergeCells('A2:I2');
            }
        ];
    }
}
